<template>
  <a-layout>
    <a-layout-content
      :style="{
        background: '#fff',
        padding: '24px',
        margin: 0,
        minHeight: '280px'
      }"
    >
      <a-row :gutter="24">
        <a-col :span="8">
          <a-button type="primary" @click="add" size="small">增加</a-button>
          <a-table
            :columns="columns"
            v-if="data.length > 0"
            :defaultExpandAllRows="true"
            :data-source="data"
            size="small"
            rowKey="id"
            :loading="loading"
            :pagination="false"
          >
            <template #name="{text,record}">
              {{ record.sort }} {{ text }}
            </template>
            <template #action="{record }">
              <a-space>
                <a-button type="primary" @click="edit(record)" size="small"
                  >编辑</a-button
                >
                <a-popconfirm
                  title="您确定删除该条信息"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="del(record.id)"
                >
                  <a-button type="primary" size="small" danger>删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>
        </a-col>
        <a-col :span="16">
          <p>
            <a-form layout="inline">
              <a-form-item>
                <a-button type="primary" size="small" @click="handleSave()"
                  >保存</a-button
                >
              </a-form-item>
            </a-form>
          </p>
          <a-form
            layout="vertical"
            :model="formState"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-form-item>
              <a-input v-model:value="formState.name" placeholder="名称" />
            </a-form-item>
            <a-form-item>
              <a-tree-select
                v-model:value="formState.parent"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择父文档"
                tree-default-expand-all
                :replaceFields="{ title: 'name', key: 'id', value: 'id' }"
              >
              </a-tree-select>
            </a-form-item>

            <a-form-item>
              <a-input v-model:value="formState.sort" placeholder="排序" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handlePrivwContent"
                >内容预览</a-button
              >
            </a-form-item>
            <a-form-item label="内容">
              <div id="content"></div>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-layout-content>
  </a-layout>
  <!--  <a-modal v-model:visible="visible" title="Title" @ok="handleOk">-->
  <!--    -->
  <!--    <template #footer>-->
  <!--      <a-button key="back" @click="handleCancel">Return</a-button>-->
  <!--      <a-button key="submit" type="primary" :loading="loading" @click="handleOk">Submit</a-button>-->
  <!--    </template>-->
  <!--  </a-modal>-->
  <a-drawer
    v-model:visible="privateVisible"
    class="custom-class"
    style="color: red"
    title="Basic Drawer"
    placement="right"
    width="900"
  >
    <div class="wangEdit" :innerHTML="privateHTML"></div>
  </a-drawer>
</template>
<script lang="ts">
import { SmileOutlined, DownOutlined } from "@ant-design/icons-vue";
import { defineComponent, onMounted, ref } from "vue";
import { docSave, docDel, docAll, idByContent } from "@/api";
import { message } from "ant-design-vue";
import { Tool } from "@/util/tool";
import { useRoute } from "vue-router";
import E from "wangeditor";

const columns = [
  {
    title: "名称",
    dataIndex: "name",
    key: "name"
  },
  {
    title: "Action",
    key: "action",
    slots: { customRender: "action" }
  }
];

export default defineComponent({
  setup: function() {
    let data = ref();
    data.value = [];
    let loading = ref(true);
    const mloading = ref<boolean>(false);
    const visible = ref<boolean>(false);
    const searchState = ref({ value: "" });
    const treeData = ref();
    const privateHTML = ref();
    const privateVisible = ref();

    let formState = ref();
    formState.value = {};
    const route = useRoute();
    let editor: any;
    onMounted(() => {
      editor = new E("#content");
      editor.config.zIndex = 0;
      editor.create();
      hander();
    });
    /*
     * 删除节点时  获取该节点的子节点
     * */
    const ids: Array<string> = [];
    const getIds = (treeData: any, id: any) => {
      for (let i = 0; i < treeData.length; i++) {
        const node = treeData[i];
        if (node.id === id) {
          ids.push(id);
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              getIds(children, children[j].id);
            }
          }
        } else {
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            getIds(children, id);
          }
        }
      }
      return treeData;
    };
    /**
     * 查询列表方法
     */
    const hander = async () => {
      data.value = [];
      let res = await docAll(route.query.ebookId);
      let ret = res.data;
      if (ret.success) {
        let tree = [];
        tree = Tool.array2Tree(res.data.content, 0);
        treeData.value = Tool.copy(tree);
        treeData.value.unshift({ name: "无", id: 0 });
        data.value = tree;
      } else {
        console.log("失败了");
      }
      loading.value = false;
    };

    /**
     * 新增/编辑
     */
    const handleSave = async () => {
      mloading.value = true;
      const queryParams: any = route.query.ebookId;
      if (!formState.value.ebookId) {
        formState.value.ebookId = queryParams;
      }
      formState.value.content = editor.txt.html();
      let res = await docSave(formState.value);
      if (res.data.success) {
        message.success({ content: "保存成功!" });
        await hander();
        mloading.value = false;
        visible.value = false;
      } else {
        message.error(res.data.message);
      }
    };
    const handleCancel = () => {
      visible.value = false;
    };
    const edit = (item: any) => {
      treeData.value = [];
      formState.value = item;
      treeData.value = Tool.copy(setDisable(data.value, item.id));
      treeData.value.unshift({ name: "无", id: 0 });
      formState.value;
      getContent(item.id);
      visible.value = true;
    };
    /*
     * 根据id获取内容
     * */
    const getContent = async (id: number) => {
      let res = await idByContent(id);
      if (res.data.success) {
        editor.txt.html(res.data.content);
      } else {
        editor.txt.html("");
      }
    };
    /**
     * 增加电子书
     */
    const add = () => {
      treeData.value = Tool.copy(data.value);
      treeData.value.unshift({ name: "无", id: 0 });
      visible.value = true;
    };
    const del = async (id: number) => {
      getIds(data.value, id);
      await docDel(ids.join(","));
      await hander();
    };
    const search = async () => {
      await hander();
    };
    /**
     * 点击预览内容按钮
     */
    const handlePrivwContent = () => {
      const html = editor.txt.html();
      privateHTML.value = html;
      privateVisible.value = true;
    };

    /*
     * 将某节点及其子孙节点全部设置未disable
     * */
    const setDisable = (treeData: any, id: any) => {
      for (let i = 0; i < treeData.length; i++) {
        const node = treeData[i];
        if (node.id === id) {
          node.disabled = true;
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              setDisable(children, children[j].id);
            }
          }
        } else {
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            setDisable(children, id);
          }
        }
      }
      return treeData;
    };
    return {
      data,
      columns,
      loading,
      visible,
      handleSave,
      handleCancel,
      edit,
      add,
      del,
      search,
      handlePrivwContent,
      searchState,
      mloading,
      formState,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      treeData,
      privateVisible,
      privateHTML
    };
  },
  components: {
    SmileOutlined,
    DownOutlined
  }
});
</script>
<style scope>
.book-cover {
  border-radius: 8%;
}
</style>
